﻿using System;
using Consul;
using Thrift.Protocol;
using Thrift.Server;
using Thrift.Transport;
using ThriftContract;

namespace ThriftServer
{
    class Program
    {
        private static string serviceName = "RPCServer";
        private static string serviceId = serviceName + Guid.NewGuid();
        static void Main(string[] args)
        {
            //服务端起来已后，会阻碍线程！因此当启动服务端以后的代码是不执行的
            Console.WriteLine("Hello World!");
            //StartThriftServerSingle();
            AddConsulServer();
            StartThriftServerS();
            StopServer();// 这个不会执行
            Console.ReadKey();
        }

        /// <summary>
        /// 单个服务
        /// </summary>
        public static void StartThriftServerSingle()
        {
            TServerTransport transport = new TServerSocket(8800); //监听8800端口
            var processor = new UserService.Processor(new
                UserServiceImpl());
            TServer server = new TThreadPoolServer(processor, transport);
            server.Serve();
        }

        /// <summary>
        /// 多个服务
        /// </summary>
        public static void StartThriftServerS()
        {
            TServerTransport transport = new TServerSocket(8800);
            var processorUserService = new UserService.Processor(new UserServiceImpl());
            var processorCalcService = new CalcService.Processor(new CalcServiceImpl());
            var processorMulti = new TMultiplexedProcessor();
            processorMulti.RegisterProcessor("userService", processorUserService);
            processorMulti.RegisterProcessor("calcService", processorCalcService);
            TServer server = new TThreadPoolServer(processorMulti, transport);
            server.Serve();

        }

        /// <summary>
        /// 向Consul注册服务
        /// </summary>
        public static void AddConsulServer()
        {
            string ip = "localhost";
            int port = 8800;
          

            using (var client = new ConsulClient(ConsulConfig))
            {
                //注册服务到 Consul
                client.Agent.ServiceRegister(new AgentServiceRegistration()
                {
                    ID = serviceId,//服务编号，不能重复，用 Guid 最简单
                    Name = serviceName,//服务的名字
                    Address = ip,//服务提供者的能被消费者访问的 ip 地址(可以被其他应用访问的 地址，本地测试可以用 127.0.0.1，机房环境中一定要写自己的内网 ip 地址)
                    Port = port,// 服务提供者的能被消费者访问的端口
                    Check = new AgentServiceCheck
                    {
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务停止多久后反注册(注销)
                        Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔，或者称为心跳间隔
                        // HTTP = $"http://{ip}:{port}/api/HealthCheck",//健康检查地址
                        TCP = "localhost:8800",
                        Timeout = TimeSpan.FromSeconds(5)
                    }
                }).Wait();//Consult 客户端的所有方法几乎都是异步方法，但是都没按照规范加上 Async 后缀，所以容易误导。记得调用后要 Wait()或者 await
            }
        }

        public static void StopServer()
        {
            using (var client = new ConsulClient(ConsulConfig))
            {
                client.Agent.ServiceDeregister(serviceId).Wait();
                Console.WriteLine("Stop!!");
            }
        }


        private static void ConsulConfig(ConsulClientConfiguration c)
        {
            c.Address = new Uri("http://127.0.0.1:8500");
            c.Datacenter = "dc1";
        }

    }
}
